﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BoxSharp;

namespace BoxSharpSearch
{
    public class BoxSharpSearch : AddonInstance
    {
        private AddonInterface myInterface;
        private Dictionary<string, SearchEngine> engines = new Dictionary<string, SearchEngine>();
        private System.Windows.Controls.ToolTip tip;

        public override void AddonMain(AddonInterface addonInterface)
        {
            myInterface = addonInterface;

            myInterface.AddonInitializing += new AddonEventHandler(myInterface_AddonInitializing);
            myInterface.AddonFinalizing += new AddonEventHandler(myInterface_AddonFinalizing);
        }

        void myInterface_AddonFinalizing()
        {
        }

        void myInterface_AddonInitializing()
        {
            string[] files = Directory.GetFiles(myInterface.Path, "*.txt");

            foreach (string file in files)
            {
                StreamReader reader = new StreamReader(file);
                string line = reader.ReadLine();

                if (line == "BoxSharp Search Engine")
                {
                    string name = reader.ReadLine();
                    string preUrl = reader.ReadLine();
                    string postUrl = reader.ReadLine();
                    string encode = reader.ReadLine();

                    SearchEngine engine = new SearchEngine(name, preUrl, postUrl, encode);
                    engines.Add(name, engine);
                }

                reader.Close();
            }

            tip = new System.Windows.Controls.ToolTip();
            tip.HasDropShadow = true;
            tip.PlacementTarget = myInterface.Box;
            tip.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
            tip.IsOpen = false;
            tip.Padding = new System.Windows.Thickness(5);
            tip.VerticalOffset = 5;

            myInterface.Box.TextChanged += new System.Windows.Controls.TextChangedEventHandler(Box_TextChanged);
            myInterface.OnCommand += new CommandEventHandler(myInterface_OnCommand);
        }

        void myInterface_OnCommand(string bscommand)
        {
            if (bscommand.ToLower().StartsWith("/search "))
            {
                foreach (string engine in engines.Keys)
                {
                    engines[engine].Query(bscommand.Substring(8));
                }

                myInterface.Box.Text = "";
            }
            else
            {
                foreach (string engine in engines.Keys)
                {
                    if (bscommand.ToLower().StartsWith("/" + engine.ToLower() + " "))
                    {
                        string query = bscommand.Substring(2 + engine.Length);

                        engines[engine].Query(query);

                        myInterface.Box.Text = "";
                        break;
                    }
                }
            }
        }

        void Box_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            if (myInterface.Box.Text.ToLower() == ("/search") || myInterface.Box.Text.ToLower().StartsWith("/search "))
            {
                tip.Content = "/search query\r\nSearch the specified query in all search engines.";
                tip.IsOpen = true;
            }
            else
            {
                bool found = false;

                foreach (string engine in engines.Keys)
                {
                    if (myInterface.Box.Text.ToLower() == ("/" + engine.ToLower()) || myInterface.Box.Text.ToLower().StartsWith("/" + engine.ToLower() + " "))
                    {
                        tip.Content = "/" + engine.ToLower() + " query\r\nSearch the specified query in " + engine + ".";
                        tip.IsOpen = true;
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    tip.IsOpen = false;
                }
            }
        }
    }

    public class SearchEngine
    {
        private string name;
        private string preURL;
        private string postURL;
        private Encoding encoding;

        public SearchEngine(string engineName, string preUrl, string postUrl, string encode)
        {
            name = engineName;
            preURL = preUrl;
            postURL = postUrl;
            encoding = Encoding.GetEncoding(encode);
        }

        public void Query(string word)
        {
            try
            {
                System.Diagnostics.Process.Start(preURL + System.Web.HttpUtility.UrlEncode(word, encoding) + postURL);
            }
            catch (System.Exception ex)
            {
                System.Windows.MessageBox.Show("Failed to send the query. Here's the error message:\r\n" + ex.Message, "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }

        public string GetQueryURL(string word)
        {
            return preURL + System.Web.HttpUtility.UrlEncode(word, encoding) + postURL;
        }

        public string Name
        {
            get
            {
                return name;
            }
        }
    }
}
